package com.telit.common.annotation.checkRepeatCommit;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.util.StringUtils;
import com.telit.common.util.JwtTokenUtils;
import com.telit.common.exception.BaseException;
import com.telit.common.response.CommonResultCode;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;


/**
 * Create by Chencf 2022/07/22
 *
 * 自定义接口防重提交切面
 * 后端定义接口3s时间内不能重复提交达到接口防重的效果，减少数据库脏数据的数量
 * 后端定义，前端也需要适当处理
 */

@Component
@Aspect
@Slf4j
public class CheckRepeatCommitAspect {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Pointcut("@annotation(com.telit.common.annotation.checkRepeatCommit.CheckRepeatCommit)")
    private void checkRepeatCommit() {

    }

    @Around("checkRepeatCommit()")
    public Object checkRepeatCommit(ProceedingJoinPoint joinPoint) throws Throwable {

        String methodName = joinPoint.getSignature().getName();
        Object target = joinPoint.getTarget();
        //得到拦截的方法
        Method method = getMethodByClassAndName(target.getClass(), methodName);
        log.info("验证是否重复提交:" + "调用方法:" + method);

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();

        String channel = "";
        String bizKey = method.getName();
        int expireTime = 0;

        // 获取当前请求方法的注解，根据注解配置获取参数
        CheckRepeatCommit checkRepeatCommit = method.getAnnotation(CheckRepeatCommit.class);

        String userNo = JwtTokenUtils.getName();
        String key;

        if (checkRepeatCommit != null) {
            //注解上的描述
            channel = checkRepeatCommit.channel();
            expireTime = checkRepeatCommit.expireTime();

            key = getRepeatCommitLock(channel, className, bizKey, userNo, expireTime);

            if (StringUtils.isEmpty(key)) {
                throw new BaseException(CommonResultCode.CHECK_REPEAT_COMMIT, "请求中");
            }
        }
        return joinPoint.proceed();
    }

    /**
     * 根据类和方法名得到方法
     */
    public Method getMethodByClassAndName(Class c, String methodName) {
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                return method;
            }
        }
        return null;
    }

    public String getRepeatCommitLock(String channel, String module, String bizKey, String userNo, int expireTime) {

        if (StringUtils.isEmpty(module) || StringUtils.isEmpty(bizKey)) {
            throw new BaseException(CommonResultCode.CHECK_REPEAT_COMMIT, "请求中");
        }

        String redisKey = channel + StrUtil.COLON + module + StrUtil.COLON + bizKey + StrUtil.COLON + userNo;

        long count = redisTemplate.opsForValue().increment(redisKey, 1);

        if (count == 1) {
            if (expireTime == 0) {
                expireTime = 60;
            }
            redisTemplate.expire(redisKey, expireTime, TimeUnit.SECONDS);
            return redisKey;
        } else {
            return null;
        }
    }

}

